import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api'

export const useSystemStore = defineStore('system', () => {
  // 状态
  const systemStats = ref(null)
  const healthStatus = ref(null)
  const loading = ref(false)
  const error = ref(null)
  
  // 计算属性
  const isConnected = computed(() => {
    return healthStatus.value?.websocket_connected || false
  })
  
  const totalCoins = computed(() => {
    return systemStats.value?.total_coins || 0
  })
  
  const totalRecords = computed(() => {
    return systemStats.value?.total_records || 0
  })
  
  // 方法
  const getSystemStats = async () => {
    try {
      loading.value = true
      error.value = null
      
      const response = await api.getSystemStats()
      systemStats.value = response.data
      
      return response.data
    } catch (err) {
      error.value = err.message || '获取系统统计失败'
      console.error('获取系统统计失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  const getHealthStatus = async () => {
    try {
      const response = await api.getHealthStatus()
      healthStatus.value = response.data
      
      return response.data
    } catch (err) {
      error.value = err.message || '获取健康状态失败'
      console.error('获取健康状态失败:', err)
      throw err
    }
  }
  
  const getSummaryStats = async () => {
    try {
      loading.value = true
      error.value = null
      
      const response = await api.getSummaryStats()
      return response.data
    } catch (err) {
      error.value = err.message || '获取汇总统计失败'
      console.error('获取汇总统计失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  const clearError = () => {
    error.value = null
  }
  
  const reset = () => {
    systemStats.value = null
    healthStatus.value = null
    loading.value = false
    error.value = null
  }
  
  return {
    // 状态
    systemStats,
    healthStatus,
    loading,
    error,
    
    // 计算属性
    isConnected,
    totalCoins,
    totalRecords,
    
    // 方法
    getSystemStats,
    getHealthStatus,
    getSummaryStats,
    clearError,
    reset
  }
})